package com.tianyadu.security.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

/**
 * @FileName: MyUserDetailsService
 * @Description: 自定义用户认证信息
 * @author: xueyj
 * @create: 2018-12-05 23:17
 */
@Slf4j
@Component
public class MyUserDetailsService implements UserDetailsService, SocialUserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
	 * (non-Javadoc)
	 *
	 * @see org.springframework.security.core.userdetails.UserDetailsService#
	 * loadUserByUsername(java.lang.String)
	 */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
      log.info("表单登陆，用户名称：【{}】", userName);
      return buildUser(userName);
    }

    /**
      * @Description: QQ授权登陆，根据用户id查询用户信息
      * @param:
      * @return:
      * @author:
      * @date:   2018/12/21 15:36
      */
    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        log.info("社交登陆，用户ID：【{}】", userId);
        return buildUser(userId);
    }

    /**
      * @Description: 构建用户信息
      * @param:
      * @return:
      * @author:
      * @date:   2018/12/21 15:36
      */
    private SocialUserDetails buildUser(String userId) {
        // 根据用户名查找用户信息
        //根据查找到的用户信息判断用户是否被冻结
        String password = passwordEncoder.encode("123456");
        log.info("数据库密码是:{}", password);
        //    根据用户名称查找用户信息 (用户信息需要实现UserDetails接口) 需要指定用户名称、密码、权限组等信息
        /**
         Username                    用户名
         Password                    密码
         isAccountNonExpired：       用户信息是否过期，true，未过期； false，已过期
         isAccountNonLocked：        用户账号是否锁定，true，未锁定； false，已锁定
         isCredentialsNonExpired：   用户密码是否过期，true，未过期； false，已过期
         isEnabled：                 用户账号是否有效，true，有效；   false，无效
         Collection<? extends GrantedAuthority> getAuthorities()： 用户权限组;
         */
        return new SocialUser(userId, password,
                true, true, true, true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}